layui.use(['form', 'layer', 'table'], function () {

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        table = layui.table;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var check_username_url = $('.check_username_url').val();
    var save_url = $('.save_url').val();


    // Table 列表
    var tableIns = table.render({
        elem: '#dataTable',
        url: datalist_url,
        //method: 'POST',
        page: true,
        cellMinWidth: 95,
        //height : "full-100",
        limit: 10,
        limits: [10, 20, 50, 100],
        id: "tableList",
        cols: [[
            /*{type: "checkbox", fixed:"left", width:50},*/
            {field: 'id', title: '序号', width: 80, align: "center"},
            {
                field: 'full_avatar', title: '用户头像', minWidth: 110, align: "center", templet: function (data) {
                    return '<a href="' + data.full_avatar + '" target="_blank"><img src="' + data.full_avatar + '" style="width: 80px;" /></a>';
                }
            },
            {field: 'username', title: '用户名', align: "center"},
            {field: 'email', title: '登录邮箱', align: "center"},
            {field: 'role_names', title: '角色', minWidth: 200, align: 'center'},
            {field: 'last_login_time', title: '最后登录时间', minWidth: 180, align: "center"},
            {
                field: 'status_name', title: '状态', align: 'center', templet: function (data) {
                    var html = '';
                    switch (data.status) {
                        case 0:
                            html += '<button class="layui-btn layui-btn-warm layui-btn-xs">' + data.status_name + '</button>';
                            break;
                        case 1:
                            html += '<button class="layui-btn layui-btn-normal layui-btn-xs">' + data.status_name + '</button>';
                            break;
                        default :
                            break;
                    }

                    return html;
                }
            },
            {
                title: '操作', fixed: "right", align: "center", minWidth: 160, templet: function (data) {
                    var html = '';
                    if (data.type != 0) {
                        html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                        html += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                    }

                    return html;
                }
            }
        ]]
    });

    // 搜索
    $(".search_btn").on("click", function () {
        var username = $('.searchBox').find('input[name=username]').val();
        var email = $('.searchBox').find('input[name=email]').val();

        if (username != '' || email != '') {
            table.reload("tableList", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    username: username,
                    email: email,
                }
            });
        } else {
            layer.msg("请选择筛选条件");
        }
    });

    // 清空搜索
    $(".reset_btn").on("click", function () {
        table.reload("tableList", {
            where: {
                username: '',
                email: '',
            }
        });
    });

    $('.add_btn').on('click', function () {
        formHtml();
    });

    // 列表操作
    table.on('tool(dataTable)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;
        // 删除
        if (layEvent === 'del') {
            layer.confirm('确定删除此数据？', {icon: 3, title: '提示信息'}, function (index) {
                $.ajax({
                    url: delete_url,
                    data: {"id": data.id},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('已删除', {icon: 1, time: 1000});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            });
        } else if (layEvent === 'edit') {
            formHtml(data);
        }
    });

    // Form 表单
    function formHtml(data) {
        var content = add_url;

        if (data) {
            content = edit_url + '?id=' + data.id;
        }

        var index = layer.open({
            title: "管理员管理",
            type: 2,
            area: ["600px", "500px"],
            content: content,
            success: function (layero, index) {
                form.render();
            }
        });
    }

    // 自定义验证规则
    form.verify({
        password: function (value) {
            var id = $('input[name=id]').val();
            if (!id) {
                if (value == '') {
                    return '请填写密码';
                }
                if (!/^[\w]{6,12}$/.test(value)) {
                    return '密码格式不正确，应为6-12位数字或字母组成';
                }
            }
        },
        confirm_password: function (value) {
            var id = $('input[name=id]').val();
            if (!id) {
                if (value == '') {
                    return '请确认密码';
                }
            }
        },
    });

    // 表单提交
    form.on("submit(laySave)", function (data) {
        var password = data.field.password;
        var confirm_password = data.field.confirm_password;

        if (password) {
            if (password != confirm_password) {
                layer.msg('两次密码不一致！');
                $('.confirm_password').focus();
                return false;
            }
        }

        var role_ids_len = $("input[name^='role_ids']:checked").length;
        if (role_ids_len <= 0) {
            layer.msg('请至少选择一个角色！', {icon: 5});
            return false;
        }

        if (data.field.status == 'on') {
            data.field.status = 1;
        } else {
            data.field.status = 2;
        }

        var username = $('.username').val();
        var ori_username = $('.username').attr('data-username');
        if (username != ori_username) {
            var url = check_username_url;
            $.ajax({
                url: url,
                type: 'POST',
                data: {'username': username},
                dataType: 'json',
                success: function (res) {
                    if (res.code == 1) {
                        layer.msg('该用户名已经存在！', {icon: 5});
                        $('.username').focus();
                        return false;
                    } else {
                        submitForm(data);
                    }
                }
            });
            return false;
        }

        submitForm(data);
    });

    // 表单提交
    function submitForm(data) {
        // 弹出loading
        var index = layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.8});

        $.ajax({
            url: save_url,
            data: data.field,
            type: "post",
            dataType: "json",
            success: function (res) {
                layer.msg(res.msg);
                if (res.code == 1) {
                    layer.closeAll("iframe");
                    //parent.window.tableIns.reload();
                    parent.layui.table.reload('tableList', {});
                }
            },
            error: function (data) {
                layer.msg("服务器无响应");
            }
        });
    }
});